package tech.aistar.controller.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import tech.aistar.entity.Picture;
import tech.aistar.service.demand.IPictureService;
import tech.aistar.util.UploadImgUtil;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/test")
public class UploadController {

    @RequestMapping("/upload")
    @ResponseBody
    public Map upload(MultipartFile myfile) {
            Map<String,String> map = new HashMap<>();

        try {
            String imgUrl = UploadImgUtil.upload(myfile.getBytes(),myfile.getOriginalFilename());
            map.put("imgUrl", imgUrl);

        } catch (IOException e) {
            e.printStackTrace();
            map.put("imgUrl", null);

        }
        //因为要作为结果返回
        return map;

    }

    @Autowired
    private IPictureService iPictureService;
    @RequestMapping("/upload1")
    @ResponseBody
    public Map upload1(MultipartFile myfile, HttpSession session) {
        Map<String,String> map = new HashMap<>();

        try {
            String imgUrl = UploadImgUtil.upload(myfile.getBytes(),myfile.getOriginalFilename());
            map.put("imgUrl", imgUrl);

            Integer uid = (Integer) session.getAttribute("userId");
            System.out.println(imgUrl);
            Picture p = new Picture();
            p.setId(uid);
            p.setUserinfoId(uid);
            p.setPath(imgUrl);
            iPictureService.updateOne(p);

//            Picture picture1 = pictureService.findPathById(userInfo.getId());
            session.setAttribute("picture1",p);

        } catch (IOException e) {
            e.printStackTrace();
            map.put("imgUrl", null);

        }
        //因为要作为结果返回
        return map;

    }
}
